import axios from 'axios';
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token';
// const baseURL = 'http://localhost:8080';
const baseURL = '/api';
const instance = axios.create({ baseURL });
//添加请求拦截器
instance.interceptors.request.use(
    (config) => {
        //请求之前的回调
        const tokenStore = useTokenStore();
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token;
        }
        return config;
    },
    //请求失败
    (err) => {
        Promise.reject(err);
    }
)
//添加响应拦截器
// import { useRoute } from 'vue-router';
// const router = useRoute();
import router from "@/router/index.js"
instance.interceptors.response.use(
    result => {
        //判断业务状态码
        if (result.data.code === 0) {
            return result.data;
        }
        //操作失败
        // alert(result.message ? result.message : "操作失败");
        ElMessage.error(result.data.message ? result.data.message : "操作失败");
        //把异步的状态转换成失败的状态
        return Promise.reject(result.data);
    },
    err => {
        //判断响应状态码，如果为401未登录，则跳转到登录页面
        if (err.response.status === 401) {
            ElMessage.error("请先登录");
            router.push("/login");
        } else {
            ElMessage.error("服务异常")
        }
        return Promise.reject(err);//把异步的状态转换成失败的状态
    }
)
export default instance;